<template>
  <div class="main">
      <div slot="header" class="clearfix">
        <el-row>
          <el-col :span="22" class="article-title">
          导入导出
          </el-col>
          <el-col :span="1">
          <el-upload
            action=""
            :auto-upload="false"
            :show-file-list="false"
            :on-change="importFile"
          >
            <el-button type="text"  style=""  >
              导入
            </el-button>
          </el-upload>
          </el-col>
          <el-col :span="1">
            <el-button
            type="text"
            @click="exportXlsx"
            >导出</el-button>
          </el-col>
        </el-row>
        
      </div>
      <div class="tl">
        <div>使用组件:XLSX</div>
        <div>安装：npm install xlsx</div>
        <div>引入包：import XLSX from 'xlsx'</div>
      </div>
      <el-table
          :data="dataList"
          border
          >

          <el-table-column 
            v-for="(item,index) in dataFirst" :key='index'
          :prop="item"
          :label="item"
         >
          </el-table-column>
          
      </el-table>
      
  </div>
</template>

<script>
import XLSX, { WorkSheet } from "xlsx";

export default {
  name: 'hzjmain',
  props: {
    msg: String
  },
  data() {
    return {
      json:[],
      dataList:[],
      dataFirst:[]
    }
  },
  methods:{
      importFile(file, fileList) {
      debugger
      const fileReader = new FileReader();
      fileReader.onload = ev => {
        try {
          const data = ev.target.result;
          const workbook = XLSX.read(data, {
            type: "binary"
          });
          //处理导入的表的数据  *************************************start***********************
          let sheet = Object.keys(workbook.Sheets)[0];
          let json = XLSX.utils.sheet_to_json(workbook.Sheets[sheet]); //获得以第一列为键名的sheet数组对象
          this.dataList=json
          for(let attr in json[0]){
            this.dataFirst.push(attr)
          }
          //处理导入的表的数据  *************************************end***********************
       
        } catch (e) {
          console.log(e);
        }
      };
      fileReader.readAsBinaryString(file.raw);
    },
    exportXlsx() {
      //处理导出的表的数据  *************************************start***********************
      let obj = {
        sheet1: [this.dataFirst]
      };
      

      for (let item of this.dataList) {
        let row = []
        for(let index of this.dataFirst){
          row.push(item[index])
        }
        obj["sheet1"].push(row);
      }
      this.downloadXlsx(obj, "陀螺仪", "信息表");
      //处理导入的表的数据  *************************************start***********************
    },
    downloadXlsx(data, fileName, sheetName) {
      fileName = (fileName || "fileName") + ".xlsx";
      sheetName = sheetName || "sheet1";
      download(data2blob(data, sheetName), fileName);

      //   下载excel文件
      function download(url, fileName) {
        if (typeof url == "object" && url instanceof Blob) {
          url = URL.createObjectURL(url); // 创建blob地址
        }
        let element = document.createElement("a");
        element.href = url;
        element.download = fileName; // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
        element.style.display = "none";
        element.click();
      }
      // 利用xlsx提供的方法将对象转成blob
      function data2blob(data, sheetName) {
        let workbook = {
          SheetNames: [],
          Sheets: {}
        };
        if (data instanceof Array) {
          workbook.SheetNames = [sheetName];
          workbook.Sheets[sheetName] = XLSX.utils.aoa_to_sheet(data);
        } else if (data instanceof Object) {
          for (const key in data) {
            if (Object.prototype.hasOwnProperty.call(data, key)) {
              const arr = data[key];
              if (arr instanceof Array) {
                workbook.SheetNames.push(key);
                workbook.Sheets[key] = XLSX.utils.aoa_to_sheet(arr);
              } else throw new Error("数据格式不正确");
            }
          }
        }
        // 生成excel的配置项
        let wopts = {
          bookType: "xlsx", // 要生成的文件类型
          bookSST: false, // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
          type: "binary"
        };
        let wbout = XLSX.write(workbook, wopts);
        let blob = new Blob([s2ab(wbout)], {
          type: "application/octet-stream"
        });
        // 字符串转ArrayBuffer
        function s2ab(s) {
          let buf = new ArrayBuffer(s.length);
          let view = new Uint8Array(buf);
          for (let i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
          return buf;
        }
        return blob;
      }
    }

  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>
